package com.dede.mypermission

import android.app.Activity
import android.app.Fragment
import android.app.FragmentManager
import android.content.Context
import android.content.pm.PackageManager
import android.support.v4.content.ContextCompat

/**
 * @author hsh
 * @date 2017/8/21 15:12.
 * @doc
 */
class MyPermission private constructor() {

    private val TAG = "MyPermission"

    companion object {

        private val myPermission = MyPermission()

        /**
         * 初始化操作
         *
         * @param activity
         */
        fun with(activity: Activity): PermissionRequest {
            return myPermission.getPermissionRequest(activity)
        }

        fun with(fragment: Fragment):PermissionRequest {
            return with(fragment.activity)
        }

        fun checkedPermission(context: Context, permission: String): Boolean {
            return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        }
    }

    private fun getPermissionRequest(activity: Activity): PermissionRequest {
        val fragmentManager = activity.fragmentManager
        val permissionFragment = getPermissionFragment(fragmentManager)
        return permissionFragment.permissionApi
    }

    private fun getPermissionFragment(fragmentManager: FragmentManager): MyPermissionFragment {
        var permissionFragment = fragmentManager.findFragmentByTag(TAG)
        if (permissionFragment == null) {
            permissionFragment = MyPermissionFragment()
            fragmentManager.beginTransaction()
                    .add(permissionFragment, TAG)
                    .commitAllowingStateLoss()
            fragmentManager.executePendingTransactions()
        }
        return permissionFragment as MyPermissionFragment
    }

}